package com.yanqu.road.server.manger;

import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.servercenter.ChannelSystemConfig;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.servergroup.ICrossServerGroup;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.entity.unioncampwar.center.CenterUnionCampWarConfigData;
import com.yanqu.road.entity.unioncampwar.center.CenterUnionCampWarGroupData;
import com.yanqu.road.logic.bussiness.servercenter.ServerBussiness;
import com.yanqu.road.pb.unionCampWar.UnionCampWar;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionCampWarGroupMgr extends TempMgr {
    private static Map<Integer, CenterUnionCampWarGroupData> serverGroupMap = new HashMap<>();
    private static List<CenterUnionCampWarGroupData> serverGroupList = new ArrayList<>();
    private static Map<Integer, List<UnionCampWar.UnionCampWarConfigTemp>> configMsgMap = new HashMap<>();

    private static List<ManagerReloadListener> managerReloadListener = new ArrayList<>();

    @Override
    public boolean init() throws Exception {
        addChannelSystemConfigLister();
        addConfigMgrReloadListener();
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        ConfigMgr.parseUnionCampWarConfig();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        reloadServerGroup();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void addChannelSystemConfigLister() {
        ChannelSystemConfigMgr.addReloadListener(() -> {
            ConfigMgr.parseUnionCampWarConfig();
            reloadServerGroup();
            getLogger().info("CrossUnionCampWarGroupMgr listen ChannelSystemConfigMgr reload");
        });
    }

    public static void addConfigMgrReloadListener() {
        ConfigMgr.addReloadListener(() -> {
            ConfigMgr.parseUnionCampWarConfig();
            reloadServerGroup();
            getLogger().info("CrossUnionCampWarGroupMgr listen ConfigMgr reload");
        });
    }

    public static void reloadServerGroup() {
        Map<Integer, CenterUnionCampWarGroupData> tempServerGroupMap = new ConcurrentHashMap<>();
        Map<String, ChannelSystemConfig> systemConfigMap = ChannelSystemConfigMgr.getSystemConfigMap(ConfigHelper.getInt("channelId"), eSystemId.UnionCampWar.getValue());
        ChannelSystemConfig groupConfig = systemConfigMap.get("SHANGBANG_SEVERGROUP_RULE");
        if (groupConfig == null) {
            getLogger().error("商帮分组配置不存在");
            return;
        }
        int minOpenDay = 0;
        ChannelSystemConfig rewardResultConfig = systemConfigMap.get("SHANGBANG_REWARD_RESULT");
        if (rewardResultConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_REWARD_RESULT,不存在");
            return;
        }

        ChannelSystemConfig winExtraRewardConfig = systemConfigMap.get("SHANGBANG_HOLD_WIN_EXTRA_REWARD");
        if (winExtraRewardConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_HOLD_WIN_EXTRA_REWARD,不存在");
            return;
        }

        ChannelSystemConfig lotteryGeneraConfig = systemConfigMap.get("SHANGBANG_LOTTERY_GENERAL");
        if (lotteryGeneraConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_LOTTERY_GENERAL,不存在");
            return;
        }

        ChannelSystemConfig lotterySpecialConfig = systemConfigMap.get("SHANGBANG_LOTTERY_SPECIAL");
        if (lotterySpecialConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_LOTTERY_SPECIAL,不存在");
            return;
        }

        ChannelSystemConfig lotteryCostConfig = systemConfigMap.get("SHANGBANG_LOTTERY_COST");
        if (lotteryCostConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_LOTTERY_COST,不存在");
            return;
        }

        ChannelSystemConfig lotteryBoxNumConfig = systemConfigMap.get("SHANGBANG_LOTTERY_BOX_NUM");
        if (lotteryBoxNumConfig == null) {
            getLogger().error("商帮配置-SHANGBANG_LOTTERY_BOX_NUM,不存在");
            return;
        }

        List<CenterUnionCampWarGroupData> tempGroupList = new ArrayList<>();

        String[] split = groupConfig.getValue().split("\\|");
        for (int i = 0; i < split.length; i++) {
            int groupId = i + 1;
            List<Integer> list = StringUtils.stringToIntegerList(split[i], "-");
            if (list.size() != 5) {
                getLogger().error("商帮分组配置参数长度错误{}", list.size());
                return;
            }
            if (i == 0) {
                minOpenDay = list.get(0);
            }

            CenterUnionCampWarGroupData groupData = new CenterUnionCampWarGroupData();
            groupData.setGroupId(groupId);
            groupData.setStartOpenDay(list.get(0));
            groupData.setGroupPerNum(list.get(1));
            groupData.setMinServerNum(list.get(2));
            groupData.setUnionNum(list.get(3));
            groupData.setNeedActive(list.get(4) == 1);
            groupData.initSHANGBANG_REWARD_RESULT(rewardResultConfig);
            groupData.initSHANGBANG_HOLD_WIN_EXTRA_REWARD(winExtraRewardConfig);
            groupData.initSHANGBANG_LOTTERY_GENERA(lotteryGeneraConfig);
            groupData.initSHANGBANG_LOTTERY_SPECIAL(lotterySpecialConfig);
            groupData.initSHANGBANG_LOTTERY_COST(lotteryCostConfig);
            groupData.initMinOpenDay(minOpenDay);

            tempGroupList.add(groupData);
            tempServerGroupMap.put(groupId, groupData);
        }

        for (int i = 0; i < tempGroupList.size(); i++) {
            if (i + 1 < tempGroupList.size()) {
                int endOpenDay = tempGroupList.get(i + 1).getStartOpenDay() - 1;
                tempGroupList.get(i).setEndOpenDay(endOpenDay);
            } else {
                tempGroupList.get(i).setEndOpenDay(Integer.MAX_VALUE);
            }
        }

        serverGroupList = tempGroupList;
        serverGroupMap = tempServerGroupMap;

        ConfigMgr.getUnionCampWarConfig().setSHANGBANG_LOTTERY_COST(lotteryCostConfig.getValue());
        ConfigMgr.getUnionCampWarConfig().setBoxNum(Integer.valueOf(lotteryBoxNumConfig.getValue()));

        configMsgMap.clear();
        for (CenterUnionCampWarGroupData groupData : serverGroupMap.values()) {
            List<UnionCampWar.UnionCampWarConfigTemp> configListMsg = getConfigListMsg(groupData.getGroupId());
            if (configListMsg.isEmpty()) {
                getLogger().error("!!!!商帮缺少后台配置,分组{}", groupData.getGroupId());
            }
            for (UnionCampWar.UnionCampWarConfigTemp configTemp : configListMsg) {
                ConfigMgr.getUnionCampWarConfig().initCenterConfig(groupData.getGroupId(), configTemp.getKey(), configTemp.getValue());
            }
        }

        notifyReload();

        getLogger().info("CrossUnionCampWarGroupMgr reload");
    }

    protected static void notifyReload(){
        for (ManagerReloadListener listener : managerReloadListener) {
            listener.notifyReload();
        }
    }

    public static void addReloadListener(ManagerReloadListener reloadListener){
        managerReloadListener.add(reloadListener);
    }

    public static Map<Integer, CenterUnionCampWarGroupData> getServerGroupMap() {
        return serverGroupMap;
    }

    public static List<CenterUnionCampWarGroupData> getServerGroupList() {
        if (null != serverGroupList) {
            return new ArrayList<>(serverGroupList);
        }
        return new ArrayList<>();
    }

    public static CenterUnionCampWarGroupData getServerGroup(int groupId) {
        return serverGroupMap.get(groupId);
    }

    public static int getGroupIdByServerId(long serverId) {
        int groupId = (int) serverId;
        CenterUnionCampWarGroupData serverGroup = getServerGroupByServerId(serverId);
        if (null != serverGroup) {
            groupId = serverGroup.getGroupId();
        }
        return groupId;
    }

    public static CenterUnionCampWarGroupData getServerGroupByServerId(long serverId) {
        CenterUnionCampWarGroupData serverGroup = null;
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        if (null == serverInfo) {
            for (CenterUnionCampWarGroupData tempGroup : serverGroupMap.values()) {
                if (tempGroup.getServerSet().contains(serverId)) {
                    serverGroup = tempGroup;
                    break;
                }
            }
        } else {
            Map<Integer, CenterUnionCampWarGroupData> dataMap = getServerGroupMap();
            if (null != dataMap) {
                for (CenterUnionCampWarGroupData tempGroup : dataMap.values()) {
                    if (tempGroup.getServerSet().contains(serverId)) {
                        serverGroup = tempGroup;
                        break;
                    }
                }
            }
        }
        return serverGroup;
    }

    public static Set<Long> getGroupServer(int groupId) {
        Set<Long> serverSet = new HashSet<>();
        CenterUnionCampWarGroupData serverGroup = getServerGroup(groupId);
        if (serverGroup == null) {
            serverSet.add((long) groupId);
        } else {
            serverSet.addAll(serverGroup.getServerList());
        }
        return serverSet;
    }

    public static List<UnionCampWar.UnionCampWarConfigTemp> getConfigListMsg(int groupId) {
        List<UnionCampWar.UnionCampWarConfigTemp> configTemps = configMsgMap.get(groupId);
        if (configTemps == null) {
            synchronized (configMsgMap) {
                configTemps = configMsgMap.get(groupId);
                if (configTemps == null) {
                    configTemps = new ArrayList<>();
                    configMsgMap.put(groupId, configTemps);

                    CenterUnionCampWarGroupData serverGroup = getServerGroup(groupId);
                    if (serverGroup != null) {
                        for (Map.Entry<String, String> entry : serverGroup.getConfigMap().entrySet()) {
                            UnionCampWar.UnionCampWarConfigTemp.Builder configTemp = UnionCampWar.UnionCampWarConfigTemp.newBuilder();
                            configTemp.setKey(entry.getKey());
                            configTemp.setValue(entry.getValue());

                            configTemps.add(configTemp.build());
                        }
                    }
                }
            }
        }

        return configTemps;
    }
}
